const util = require("../../../utils/util.js");
const app = getApp()
Page({
  data: {
    isShow: false,                        // Back组件显示隐藏
    pageUrl: '/pages/index/index',        // Back组件跳转页面地址
    time_ary: ['0', '3', ':', '0', '0'],
    leaveStatus: false, // 是否离开页面
    avatar: "",         // 头像
    nickName: "",       // 昵称
    timer: {            // 状态控制
      state: false,     // false：未开始 || true：进行中
      success: false,   // 成功弹框状态
      fail: false,      // 失败弹框状态
      mask: false,      // 黑色遮罩状态
      mask_slide: false // 挑战中禁止swiper滑动
    },
    isIphoneX: app.globalData.isIphoneX,
    clocker: null, // 倒计时--定时动画
    minute: "01",  // 倒计时--分钟
    second: "00",  // 倒计时--秒数
    timeSpace: 0,  // 倒计时--时长区间
    leftTime: 0,   // 倒计时--剩余时间
    progressBar: 0,// 倒计时--控制树苗成长程度
    progressBarMove:'100%',// 倒计时进度条02

    swiperMove: false, // 禁止滑块滑动
    music: {           // 音乐控制
      src: "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute_huabang.mp3", //音乐路径
      state: true,     //音乐状态
      audioCtx_bg: "", //背景音乐
    },
    currentItemId: 0,  // 当前第几swiper
    groupTreeType: [{
        'id': 0,
        "tree_0": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___huabang_1.png",
        "tree_1": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___huabang_2.png",
        "tree_2": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___huabang_3.png",
        "tree_3": "http://elion.oss-cn-beijing.aliyuncs.com/forest2/earthOneMinute___huabang_error.png",
        "imageUrl_bg": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___bg--huabang.png",
        "music_url": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute_huabang.mp3",
        "success_price": "3库币",
        "success_peo_num": 0,
        "time_consume": 0, // 小树 || 中树 || 大树
        "name": "花棒",
        "title": "美丽之树",
        "time_slot": 3,
      },
      {
        'id': 1,
        "tree_0": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___zhangzisong_1.png",
        "tree_1": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___zhangzisong_2.png",
        "tree_2": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___zhangzisong_3.png",
        "tree_3": "http://elion.oss-cn-beijing.aliyuncs.com/forest2/earthOneMinute___zhangzisong_error.png",
        "imageUrl_bg": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___bg--zhangzisong.png",
        "music_url": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute_zhangzisong.mp3",
        "success_price": "5库币",
        "success_peo_num": 0,
        "time_consume": 0, // 小树 || 中树 || 大树
        "name": "樟子松",
        "title": "长青之树",
        "time_slot": 5,
      },
      {
        'id': 2,
        "tree_0": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___huyang_1.png",
        "tree_1": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___huyang_2.png",
        "tree_2": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___huyang_3.png",
        "tree_3": "http://elion.oss-cn-beijing.aliyuncs.com/forest2/earthOneMinute___huyang_error.png",
        "imageUrl_bg": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute___bg--huyang.png",
        "music_url": "http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute_huyang.mp3",
        "success_price": "15库币",
        "success_peo_num": 0,
        "time_consume": 0, // 小树 || 中树 || 大树
        "name": "胡杨",
        "title": "幸运之树",
        "time_slot": 15,
      }
    ],
    shareLinkCode: "", // 二维码code
    backgroundColorArray: ['#ac79f9', '#34d39e', '#fd9169'], // 导航颜色切换
    backgroundTitleArray: ['花棒', '章子松', '胡杨'] // 导航文字切换
  },
  // 页面渲染
  onReady() {
    /*
     * 默认进入播放音乐
     * autoplay:自动播放
     * loop:循环播放
     * src:音乐资源
    */
    this.data.music.audioCtx_bg = wx.createInnerAudioContext()
    this.data.music.audioCtx_bg.autoplay = true
    this.data.music.audioCtx_bg.loop = true
    this.data.music.audioCtx_bg.src = this.data.music.src
  },
  // 关闭音乐和倒计时
  clearMusicTime() {
    // 关闭音乐
    this.data.music.audioCtx_bg.stop()
    // 停止倒计时
    this.stopCountdown()
  },
  // 页面加载
  onLoad(options) {
    // 如果为分享进入，则显示分享返回按钮
    let shareType = options.shareType
    if (shareType) {
      this.setData({
        isShow: true,
      })
    }
  },
  // 页面展示
  onShow() {
    // 初始化数据
    this.init()
    // 保持手机屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: true,
    });
    // 如果离开页面情况处理
    let timerState = this.data.timer.state // 开始计时了 ture
    let leaveStatus = this.data.leaveStatus // 离开页面了 ture
    if (timerState && leaveStatus) {
      this.setData({
        ['timer.fail']: true
      })
    }
  },
  // 页面隐藏
  onHide() {
    // 清空计时器
    this.stopCountdown();
    // 音乐状态改变
    this.music_state_change();
    // 是否离开页面
    this.setData({
      leaveStatus: true,
    })
  },
  // 页面卸载
  onUnload() {
    // 清空音乐和计时
    this.clearMusicTime()
  },
  // 分享
  onShareAppMessage: function(res, callback) {
    var titles = "";
    var imageUrls = '';
    var paths = '';
    titles = "我赢得了地球一刻钟的挑战，你也来参与吧";
    imageUrls = 'http://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/earthOneMinute__share.png';
    paths = 'packageEarthOneMinute/pages/index/index?scene=' + this.data.shareLinkCode + '&shareType=' + 'shareType';
    return {
      title: titles,
      path: paths,
      imageUrl: imageUrls,
    }
  },
  // 初始化数据
  init: function() {
    // this.shareLinkCode();
    // this.getSuccessPeopleNum();
    this.setData({
      avatar: "https://wx.qlogo.cn/mmhead/DMg8ibuHibWeys8ib2GOxYib9QG7Tss2ClnFcxjTl1DDvdE/132",
      nickName: "小风儿",
    })
  },
  // 新用户
  onLoginCompleted: function(e) {
    this.init()
  },
  // 活动动态-获取总人数
  getSuccessPeopleNum: function() {
    util.newRequest.post('/Earth/getSuccessPeopleNum', {})
      .then(res => {
        let groupTreeType = this.data.groupTreeType
        groupTreeType.forEach((item, index) => {
          item.success_peo_num = res.data.data[index].peoNum
        })
        this.setData({
          groupTreeType: groupTreeType
        })
      })
      .catch(res => console.log('获取总人数异常', res))
  },
  // 获取分享的code
  shareLinkCode: function() {
    util.newRequest.post('/QrcodeInfo/getUserQrcode', {
        path: 'packageEarthOneMinute/pages/index/index'
      })
      .then(res => {
        // console.log('获取分享的code', res)
        this.setData({
          shareLinkCode: res.data.data.code
        })
      })
      .catch(res => console.log('获取分享的code失败', res))
  },
  // 进入规则页面
  enter_desc: function() {
    wx.navigateTo({
      url: "../desc/index",
    })
  },
  /*
   * swiper背景音乐切换
   */
  change_music: function(str) {
    this.data.music.audioCtx_bg.src = str;
    this.setData({
      ['music.state']: true
    })
  },
  /*
   * 背景音乐
   * 播放
   * 暂停
   */
  music_state_change: function() {
    if (this.data.music.state) {
      this.data.music.audioCtx_bg.pause();
    } else {
      this.data.music.audioCtx_bg.play();
    }
    this.setData({
      ['music.state']: !this.data.music.state
    })
  },
  // Swiper切换
  swiperChange: function(e) {
    let currentItemId = e.detail.currentItemId                          // 切换到第几帧Swiper
    let currentMusic = this.data.groupTreeType[currentItemId].music_url // 播放音乐资源
    let selectTreePicture = this.data.groupTreeType[currentItemId].imageUrl_bg //选择的树木图片
    // 设置背景颜色
    let currentBackgroundColorArray = this.data.backgroundColorArray[currentItemId];
    let currentbackgroundTitleArray = this.data.backgroundTitleArray[currentItemId];
    let fontColor = "#ffffff"
    util.setNavigationStyle(currentBackgroundColorArray, fontColor);
    util.setNavigationTitle(currentbackgroundTitleArray);
    //更换音乐
    this.change_music(currentMusic)
    //重新游戏
    this.game_new()
    this.setData({
      currentItemId: currentItemId,
      selectTreePicture: selectTreePicture
    }, () => {
      this.reset_timer()
    })
  },
  game_new: function() { //重新挑战
    this.setData({
      ['timer.success']: false,
      ['timer.fail']: false,
      ['timer.state']: false,
      ['timer.mask']: false,
      ['timer.mask_slide']: false,
      leaveStatus: false,
      progressBarMove: '100%'
    })
    // 重置时间
    this.reset_timer()
  },
  game_start: function() { //开始游戏
    this.setData({
      ['timer.state']: true,
      ['timer.mask_slide']: true,
    });
    this.startCountdown(this.data.groupTreeType[this.data.currentItemId].time_slot);
  },
  // 游戏成功
  game_cuccess: function() {
    this.setData({
      ['timer.state']: false,
      ['timer.success']: true,
      ['timer.mask']: true,
    });
    this.reset_timer();
    util.newRequest.post('/Earth/submitEarthQuarter', {
        treeType: this.data.currentItemId
      })
      .then(res => {

      })
      .catch(res => console.log('submitEarthQuarter图片异常', res))
  },
  // 游戏失败
  game_fail: function() {
    this.setData({
      ['timer.state']: false,
      ['timer.fail']: true,
      ['timer.mask']: true,
      progressBarMove:'100%',
    });
    this.reset_timer();
    this.stopCountdown();
  },
  // 开始倒计时
  startCountdown: function(time_slot) {
    this.countDown(time_slot)
  },
  // 清空定时器
  stopCountdown: function() {
    clearInterval(this.data.clocker)
  },
  /*
   * 重置数据
   * 时间
   * 树木基本数据归0
   */
  reset_timer: function() {
    // 重置倒计时时间
    let time_ary = [];
    switch (parseInt(this.data.currentItemId)) {
      case 0:
         time_ary = ['0', '3', ':', '0', '0'];
        break;
      case 1:
         time_ary = ['0', '5', ':', '0', '0'];
        break;
      default:
         time_ary = ['1', '5', ':', '0', '0'];
    }
    this.setData({
      time_ary: time_ary
    })
  },
  // 倒计时
  countDown: function(timeLong) {
    // 结束时间秒数
    let endTime = new Date().getTime() + (timeLong * 60 * 1000)
    // 时长(用以计算进度条百分数)
    let timeSpace = endTime - new Date().getTime()
    // 实现倒计时逻辑代码
    this.data.clocker = setInterval(() => {
      // 剩余时间
      let leftTime = endTime - new Date().getTime()
      // 进度条百分数
      // let progressBarMove = (1 - (leftTime / timeSpace)).toFixed(2) * 100 + '%'
      let progressBarMove = (leftTime / timeSpace).toFixed(2) * 100 + '%'
      // console.log('1----------------', progressBarMove)
      let progressBar = (1 - (leftTime / timeSpace)).toFixed(2) * 100
      // 切换树苗图片状态
      let currentItemId = this.data.currentItemId || 0 // 当前切换siwper值
      let groupTreeType = this.data.groupTreeType      // 所有树数据
      let time_consume = 0
      if (progressBar >= 0 && progressBar < 30) {
        time_consume = 0
      } else if (progressBar >= 30 && progressBar < 80) {
        time_consume = 1
      } else {
        time_consume = 2
      }

      // 设置修改数据
      groupTreeType.forEach((item) => {
        if (item.id == currentItemId) {
          item.time_consume = time_consume
        }
      })
      this.setData({
        groupTreeType: groupTreeType
      })

      // 倒计时结束
      if (leftTime < 1) {
        clearInterval(this.data.clocker);
        this.setData({
          minute: '00',
          second: '00',
          clocker: null,
          timeSpace: timeSpace,
          leftTime: leftTime,
          progressBar: progressBar,
          progressBarMove: progressBarMove
        })
        this.game_cuccess();
        return;
      }
      // 倒计时进行中
      let leftSecond = parseInt(leftTime / 1000)
      //天数
      let Day = Math.floor(leftSecond / (60 * 60 * 24))
      //小时
      let Hour = Math.floor((leftSecond - Day * 24 * 60 * 60) / 3600)
      //分钟
      let Minute = Math.floor((leftSecond - Day * 24 * 60 * 60 - Hour * 3600) / 60)
      //秒数
      let Second = Math.floor(leftSecond - Day * 24 * 60 * 60 - Hour * 3600 - Minute * 60)
      if (Minute >= 0 && Second >= 0) {
        let Minute_1 = Minute < 10 ? '0' + Minute : Minute;
        let Second_1 = Second < 10 ? '0' + Second : Second;
        let ary = (Minute_1 + ":" + Second_1).split('');

        this.setData({
          minute: Minute_1,
          second: Second_1,
          timeSpace: timeSpace,
          leftTime: leftTime,
          progressBar: progressBar,
          progressBarMove: progressBarMove,
          time_ary: ary
        })
      }
    }, 1000)
  },

})
